<template>
  <div
    class="img-down-preview"
    :style="{
      width,
      height,
    }"
  >
    <el-image
      ref="imgDownPreviewRef"
      :style="{
        width,
        height,
      }"
      :fit="fit"
      :src="url"
    >
      <template #placeholder>
        <div class="image-slot">
          <el-icon><IconPicture /></el-icon>
        </div>
      </template>
    </el-image>
    <div v-if="url" class="handle-box">
      <div>
        <el-icon class="icon-style" @click="onClickPreview"><View /></el-icon>
        <el-icon class="icon-style" @click="onClickDownload(url)"><Download /></el-icon>
      </div>
    </div>
  </div>
  <el-image-viewer
    v-if="showImageViewer && url"
    :teleported="true"
    :url-list="[url]"
    @close="onClickClose"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import { DownloadService } from '@/services/http';
/**
 *@img-down-preview
 */
defineOptions({ name: 'ImgDownPreview' });
// props
/**
 * @props
 */
defineProps({
  width: {
    type: String,
    default: '122px'
  },
  height: {
    type: String,
    default: '80px'
  },
  url: {
    type: String,
    default: ''
  },
  fit: {
    type: String,
    default: 'contain'
  }
});
const showImageViewer = ref(false);
const onClickPreview = () => {
  showImageViewer.value = true;
};
const onClickClose= () => {
  showImageViewer.value = false;
};
const onClickDownload = async (url: string) => {
  await DownloadService.downloadImage(url);
};
</script>

<style lang="scss" scoped>
.img-down-preview {
  position: relative;
  display: inline-flex;

  .handle-box {
    position: absolute;
    z-index: 11;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background: rgb(0 0 0 / 50%);
    opacity: 0;
  }

  &:hover {
    .handle-box {
      opacity: 1;
    }
  }

  .icon-style {
    margin-right: 10px;
    color: #fff;
    cursor: pointer;
  }

  :deep(.el-image) {
    background: #fafafa;
  }

  .image-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    font-size: 30px;
  }

  .image-slot .el-icon {
    font-size: 30px;
  }
}
</style>
